<template>
  <div class="sendOrders-Setting">
    <el-table-form ref="form" :model="query">
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="0.2">
        <el-checkbox v-model="query.option" label="包含下级" />
      </el-form-item>
      <el-form-item label="策略名称:">
        <el-input v-model.trim="query.strategyName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="自动派单开关:">
        <el-select v-model="query.isOpen" placeholder="请选择">
          <el-option
            v-for="item in isOpenList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[50502,1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>

    <div style="margin-bottom: 10px;">
      <el-button
        v-permission="[50502,2]"
        type="primary"
        @click="batch(true)"
      >批量开启</el-button>
      <el-button
        v-permission="[50502,3]"
        type="danger"
        @click="batch(false)"
      >批量关闭</el-button>
      <el-button
        v-permission="[50502,4]"
        type="primary"
        @click="batchBind"
      >批量绑定</el-button>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @selection-change="selectionChange"
      @fetch="fetchData"
    />
    <el-dialog
      v-el-drag-dialog
      :title="'选择自动派单策略'"
      :visible.sync="visible"
      width="824px"
      @closed="reset"
    >
      <lb-table
        ref="lbTable1"
        v-el-height-adaptive-table="{ bottomOffset: 10 }"
        v-loading="$loadingPlugin.fetchData1"
        border
        element-loading-text="加载中"
        :column="column1"
        :data="tableData1.data"
        custom-column
        @fetch="fetchData1"
      />
      <div slot="footer" class="dialog-footer">
        <el-button :loading="$loadingPlugin.del" type="danger" @click="cancel()">
          取消
        </el-button>
        <el-button :loading="$loadingPlugin.success" type="primary" @click="sumbit()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <sendOrdersTacticsDetail ref="sendOrdersTacticsDetail" />
  </div>
</template>

<script>
  import { strategyList, dispatchList, dispatchSaveOrUpdate, dispatchDelete } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { parseTime } from '@/utils'
  import { mapGetters } from 'vuex'
  import sendOrdersTacticsDetail from '../sendOrdersTactics/sendOrdersTacticsDetail'
  export default {
    name: '',
    components: {
      sendOrdersTacticsDetail
    },
    data() {
      return {
        query: {
          orgSNNo: '',
          strategyName: '',
          isOpen: 0,
          option: false
        },
        isOpenList: [{ desc: '全部', value: 0 }, { desc: '开', value: 1 }, { desc: '关', value: -1 }],
        treeData: [],
        tableData: {
          total: 0,
          data: []
        },
        visible: false,
        tableData1: {
          data: []
        },
        selectionList: [],
        orgIds: [],
        currentRow: null,
        radioCurrent: null
      }
    },
    computed: {
      ...mapGetters(['orgList', 'userInfo', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          {
            type: 'selection',
            selectable: this.selected
          },
          { label: '所属机构', prop: 'orgName' },
          { label: '自动派单开关', align: 'center', width: 120,
            render: (h, { row }) => (
            <el-switch
            v-model={row.isOpen}
            active-color='#13ce66'
            inactive-color='#ff4949'
            onChange={() => this.changeOpen(row)}>
            </el-switch>
          ) },
          {
            prop: 'strategyCode',
            label: '自动派单策略ID',
            width: 120,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row)}>
              {row.strategyCode}
            </el-link>
          )
          },
          { label: '自动派单策略名称', prop: 'strategyName' },
          { label: '自动派单时间', prop: 'dispatchTime', width: 140 },
          { label: '最后一次操作人', prop: 'lastOperator', width: 120 },
          { label: '最后一次操作时间',
            prop: 'modifyTime',
            width: 140,
            render: (h, { row }) => (
                <span>
                {row.modifyTime && parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}')}
                </span>
          ) },
          {
            label: '操作',
            className: 'action-col',
            width: 140,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
              <div>
                  <el-link
                    v-permission={[50502, 5]}
                    underline={false}
                    size='mini'
                    onClick={() => this.bind(row, $index)}
                  >
                    绑定策略
                  </el-link>
                  <el-link
                    v-permission={[50502, 6]}
                    v-show={row.strategyCode}
                    underline={false}
                    size='mini'
                    type='danger'
                    onClick={() => this.noBind(row, $index)}
                  >
                    解除绑定
                  </el-link>
              </div>
              )
            }
          }
        ]
      },
      column1: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          {
            label: '',
            width: '35',
            align: 'center',
            render: (h, { row }) => (
              <el-radio v-model={this.radioCurrent} label={row.strategyCode} onChange={() => this.handleCurrentChange(row)}></el-radio>
            )
          },
          {
            prop: 'strategyCode',
            label: '策略ID',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row)}>
              {row.strategyCode}
            </el-link>
          )
          },
          { label: '策略名称', prop: 'strategyName' },
          { label: '创建策略人', prop: 'createUser' },
          {
            label: '创建时间',
            prop: 'createTime',
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            label: '操作',
            className: 'action-col',
            width: 130,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
              <div>
                  <el-link
                    v-permission='7'
                    underline={false}
                    size='mini'
                    onClick={() => this.openDetail(row, $index)}
                  >
                    详情
                  </el-link>
              </div>
              )
            }
          }
        ]
      }
    },
    created() {
      this.getTreeData()
      this.fetchData1()
    },
    mounted() {},
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgSNNo = this.userInfo.orgSNNo
        this.query.orgId = this.userInfo.orgId
        this.query.orgName = this.userInfo.orgName
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.orgId = value.orgId
        this.query.orgName = value.orgName
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        query.orgId = this.query.option ? 0 : this.query.orgId
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        const res = await dispatchList(query)
        this.tableData.data = res.data.rows
        await this.tableData.data.forEach(item => {
          item.isOpen = item.isOpen === 1
        })
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      async fetchData1() {
        const res = await strategyList({})
        this.tableData1.data = res.data
        this.tableData1.data.forEach(item => {
          item.radioCurrent = '0'
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7 || row.orderStatus === 3) {
          // 7:已退单 3:退单申请中
          return 'danger-row'
        }
        if (row.orderStatus === 9 || row.orderStatus === 12) {
          // 9:退货申请中 12:已退货
          return 'giveup-row'
        }
        return ''
      },
      // 打开策略详情
      async openDetail(row) {
        await this.$refs.sendOrdersTacticsDetail.open(row)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 勾选事件
      selectionChange(val) {
        this.selectionList = val
        // console.log(val)
      },
      reset() {

      },
      // 选中行
      handleCurrentChange(val) {
        // console.log(val)
        this.currentRow = val
      },
      // 绑定策略
      bind(row, index) {
        if (this.tableData1.data.length === 0) {
          this.$message.error('当前没有可用的自动派单策略，请先去自动派单策略页面新增自动派单策略，再绑定派单策略')
          return
        }
        if (row.strategyCode && row.isOpen) {
          this.$message.error('当前站点已开启自动派单，如需更换策略，请先关闭自动派单功能')
          return
        }
        this.radioCurrent = null
        this.radioCurrent = row.strategyCode
        this.orgIds = []
        this.visible = true
        this.orgIds.push(row.orgId)
        this.chooseBatchBind = false
      },
      // 解除绑定策略
      noBind(row, index) {
        if (row.strategyCode && row.isOpen) {
          this.$message.error('当前站点已开启自动派单，如需解除绑定，请先关闭自动派单功能')
          return
        }
        // 7,"解绑派单策略"
        dispatchDelete({ orgId: row.orgId, operatorAction: 7 }).then(() => {
          this.$notify({
            title: '提示',
            message: `解除绑定成功`,
            type: 'success',
            duration: 2000
          })
          this.$refs.lbTable.fetch()
        }).catch(err => { console.log(err) })
      },
      // 多选禁用
      selected(row, index) {
        // if (!row.strategyCode) {
        //   return false //不可勾选
        // } else {
        //   return true; //可勾选
        // }
        return true
      },
      // 批量开启
      async batch(isOpen) {
        if (this.selectionList.length === 0) {
          this.$message.error('请选择需要批量操作的数据！')
          return
        }
        this.orgIds = []
        let isNoBind = 0
        await this.selectionList.forEach(item => {
          this.orgIds.push(item.orgId)
          if (!item.strategyCode) {
            isNoBind++
          }
        })
        this.$confirm(`确定批量${isOpen ? '开启' : '关闭'}自动派单吗`, '提示', {
          type: 'warning'
        }).then(() => {
          const form = {
            isOpen: isOpen ? 1 : -1,
            orgIds: this.orgIds.join(','),
            operatorAction: isOpen ? 3 : 4 // 3,批量开启 4,关闭自动派单
          }
          if (isNoBind && isOpen) {
            this.$confirm(`勾选的站点有的没有绑定自动派单策略，没有绑定自动派单策略的站点将不会${isOpen ? '开启' : '关闭'}自动派单`, '提示', {
              type: 'warning'
            }).then(() => {
              dispatchSaveOrUpdate(form).then(res => {
                this.$refs.lbTable.fetch()
                this.$notify({
                  title: '提示',
                  message: `批量${isOpen ? '开启' : '关闭'}自动派单成功`,
                  type: 'success',
                  duration: 2000
                })
                this.visible = false
              }).catch(err => { console.log(err) })
            }).catch(() => {
              this.$message.info('已取消')
            })
          } else {
            dispatchSaveOrUpdate(form).then(res => {
              this.$refs.lbTable.fetch()
              this.$notify({
                title: '提示',
                message: `批量${isOpen ? '开启' : '关闭'}自动派单成功`,
                type: 'success',
                duration: 2000
              })
              this.visible = false
            }).catch(err => { console.log(err) })
          }
        }).catch(() => {
          this.orgIds = []
          this.$message.info('已取消')
        })
      },
      // 批量绑定
      async batchBind() {
        if (this.selectionList.length === 0) {
          this.$message.error('请选择需要批量操作的数据！')
          return
        }
        if (this.tableData1.data.length === 0) {
          this.$message.error('当前没有可用的自动派单策略，请先去自动派单策略页面新增自动派单策略，再绑定派单策略')
          return
        }
        this.orgIds = []
        let isOpenSum = 0
        this.isBind = 0
        await this.selectionList.forEach(item => {
          this.orgIds.push(item.orgId)
          if (item.isOpen) {
            isOpenSum++
          }
          if (item.strategyCode) {
            this.isBind++
          }
        })
        if (isOpenSum) {
          this.$message.error('批量绑定派单策略失败，所勾选的站点有已开启自动派单的，如需绑定新的派单策略，请先关闭自动派单功能')
          return
        }
        this.radioCurrent = null
        this.visible = true
        this.chooseBatchBind = true
      },
      // 更改派单开关
      changeOpen(row) {
        console.log(row)
        if (!row.strategyCode) {
          row.isOpen = !row.isOpen
          this.$message.error('当前站点没有绑定自动派单策略，请先绑定自动派单策略在开启自动派单')
          return
        }
        this.$confirm(`确定${row.isOpen ? '开启' : '关闭'}自动派单吗`, '提示', {
          type: 'warning'
        }).then(() => {
          const form = {
            isOpen: row.isOpen ? 1 : -1,
            orgIds: row.orgId,
            operatorAction: row.isOpen ? 1 : 2 // 1,开启 2,关闭自动派单
          }
          dispatchSaveOrUpdate(form).then(res => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: `自动派单${row.isOpen ? '开启' : '关闭'}成功`,
              type: 'success',
              duration: 2000
            })
            this.visible = false
          }).catch(err => { console.log(err) })
        }).catch(() => {
          row.isOpen = !row.isOpen
          this.$message.info('已取消')
        })
      },
      // 取消
      cancel() {
        this.visible = false
      },
      // 保存
      async sumbit() {
        if (!this.currentRow) {
          this.$message.error('请选择自动派单策略')
          return
        }
        if (this.chooseBatchBind && this.isBind > 0) {
          this.$confirm(`所选站点有的已绑定自动派单策略，如果更换绑定策略后，系统会先关闭之前绑定的策略，执行最新绑定的自动派单策略？`, '提示', {
            type: 'warning'
          }).then(() => {
            const form = {
              strategyCode: this.currentRow.strategyCode,
              strategyName: this.currentRow.strategyName,
              dispatchTime: this.currentRow.dispatchTime,
              orgIds: this.orgIds.join(','),
              operatorAction: this.chooseBatchBind ? 6 : 5 // 6,批量绑定派单策略
            }
            dispatchSaveOrUpdate(form).then(res => {
              this.$refs.lbTable.fetch()
              this.$notify({
                title: '提示',
                message: '批量绑定自动派单策略成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
            }).catch(res => {

            })
          }).catch(() => {
            this.$message.info('已取消')
          })
          return
        }
        const form = {
          strategyCode: this.currentRow.strategyCode,
          strategyName: this.currentRow.strategyName,
          dispatchTime: this.currentRow.dispatchTime,
          orgIds: this.orgIds.join(','),
          operatorAction: this.chooseBatchBind ? 6 : 5 // 5,"绑定派单策略"
        }
        dispatchSaveOrUpdate(form).then(res => {
          this.$refs.lbTable.fetch()
          this.$notify({
            title: '提示',
            message: '绑定自动派单策略成功',
            type: 'success',
            duration: 2000
          })
          this.visible = false
        }).catch(res => {

        })
      }
    }
  }

</script>
<style lang='scss' scoped>
</style>
